from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.exceptions import ValidationError
from orders.services import OrderService

@login_required
def order_create(request, restaurant_id):
    if request.method == 'POST':
        try:
            order = OrderService.create_order(
                user=request.user,
                restaurant_id=restaurant_id,
                items_data=request.POST,
                delivery_address=request.POST.get('delivery_address')
            )
            messages.success(request, '订单创建成功！')
            return redirect('order_detail', order_id=order.id)
        except ValidationError as e:
            messages.error(request, str(e))
        except Exception as e:
            messages.error(request, '创建订单失败，请重试')
        return redirect('restaurant_detail', restaurant_id=restaurant_id)
    
    return redirect('restaurant_detail', restaurant_id=restaurant_id)

@login_required
def order_list(request):
    orders = OrderService.get_user_orders(request.user)
    return render(request, 'orders/order_list.html', {'orders': orders})

@login_required
def order_detail(request, order_id):
    order = OrderService.get_order_detail(order_id, request.user)
    return render(request, 'orders/order_detail.html', {'order': order})